package com.chenfei.api.filter;

import com.chenfei.api.config.CrossConf;
import com.chenfei.api.constant.Constants;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author chenfei
 * @description
 * @since 2018/2/8
 */
@Slf4j
public class CrossFilter extends ZuulFilter{
	@Autowired
	private CrossConf crossConf;
	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() {
		RequestContext cxt = RequestContext.getCurrentContext();
		HttpServletRequest request = cxt.getRequest();
		String method = request.getMethod();
		String origin = request.getHeader(Constants.HTTP_HEADER_ORIGIN);
		log.info("url:{},method:{},origin:{}",request.getRequestURI(),method,origin);
		
		String allowOrigin = this.gennerateAllowOrigin(origin);
		if(StringUtils.isNotEmpty(allowOrigin)){
			HttpServletResponse response = cxt.getResponse();
			response.setHeader("Access-Control-Allow-Origin", allowOrigin);
			response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE");
			response.setHeader("Access-Control-Max-Age", "3600");
			response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
			response.setHeader("Access-Control-Allow-Headers", "Content-Type,Authorization,Accept,X-Requested-With,POWERED-BY-MENGXIANHUI,logintoken");
		}
		
		
		if(StringUtils.equalsIgnoreCase(method, Constants.HTTP_METHOD_OPTIONS)){
			cxt.setSendZuulResponse(false);
		}
		
		return null;
	}

	@Override
	public String filterType() {
		return "pre";
	}

	@Override
	public int filterOrder() {
		return 1;
	}

	private String gennerateAllowOrigin(String origin){
		String allowOrigin = null;
		
		List<String> allowOriginList = this.crossConf.getAllowOriginList();
		if(allowOriginList.contains(Constants.ALLOW_ALL_ORIGIN)){
			allowOrigin = Constants.ALLOW_ALL_ORIGIN;
		}else if(allowOriginList.contains(origin)){
			allowOrigin = origin;
		}
		
		return allowOrigin;
	}
}
